<?php

namespace app\index\controller\session;

use app\index\service\SessionTestService;
use app\index\service\SessionWechatService;
use app\index\traits\SessionTrait;
use app\index\traits\TempTokenCheckTrait;
use ShidianUtil\Api\Tencent\Wechat\Util\WechatUtil;
use ShidianUtil\Thinkphp\Response\ApiResponse;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Log;
use think\Request;

/**
 * 微信小程序登录
 * Class WechatMiniprogram
 * @package app\session\controller
 */
class WechatMiniprogram
{
    use TempTokenCheckTrait;
    use SessionTrait;

    private Request $request;

    private SessionWechatService $service;
    private SessionTestService $testService;

    public function __construct(Request $request, SessionWechatService $thirdService, SessionTestService $testService)
    {
        $this->service = $thirdService;
        $this->request = $request;
        $this->testService = $testService;
    }

    /**
     * 微信登录
     * @return ApiResponse
     * @url /session/wechat_miniprogram/save
     */
    public function save(): ApiResponse
    {
        $request = $this->request;

        // 获取和验证登录信息（手机号，邀请码）
        $loginInfo = $this->getLoginInfo($request);
        $phone = $loginInfo['phone'];
        $inviteCode = $loginInfo['inviteCode'];

        // 渠道链路
        ['pf' => $pf, 'chain' => $chain, 'promotionGroupId' => $promotionGroupId] = getChainParams();

        // 获取三方登录信息
        $wx_app = $request->param('wx_app', MINIPROGRAM);
        $code = $request->param('code');
        $data = WechatUtil::jscode2session($wx_app, $code);
        $errcode = $data['errcode'] ?? 0;
        if ($errcode !== 0 && $errcode !== '0') {
            Log::warning('微信授权登录失败' . json_encode($data));
            throw new ValidateException('授权登录失败');
        }


        $data['openidWeiXin'] = $data['openid'] ?? '';
        unset($data['openid']);

        $data['phone'] = $phone;
        $data['inviteCode'] = $inviteCode;
        $data['nickname'] = $request->param('nickname');
        $data['headImgUrl'] = $request->param('headImgUrl');
        $data['memberDraft'] = $request->param('memberDraft');

        $data['pf'] = $pf;
        $data['chain'] = $chain;
        $data['promotionGroupId'] = $promotionGroupId;

        // 测试账号登录
        if (in_array($phone, Config::get('member.testAccount', []))) {
            return ApiResponse::success($this->testService->login($request->param(), $data));
        }

        // 登录
        return ApiResponse::success($this->service->login($data));
    }
}
